package com.example.fyptest3;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.example.fyptest3.sqlite.helper.*;
import com.example.fyptest3.sqlite.model.*;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ActionBar.LayoutParams;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;

public class AssignmentActivity extends Activity implements OnClickListener{

	DataBaseHelper db;
	Button[] button_categories;
	ImageView[][] iv_tasks;
	TextView[] textview_tasks;
	private int currentCategory = 0;
	List<Task> task_list;
	LinearLayout LL1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_assignment);
		
		//change title text to
		setTitle("<< Albums  -  Assignment Album Menu");
				
		//change title bar color to CYAN
		ActionBar bar = getActionBar();
		bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00C4CD")));
				
		//change title bar text to WHITE
		int actionBarTitleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
		if (actionBarTitleId >0){
			TextView title = (TextView)findViewById(actionBarTitleId);
			if (title != null){
				title.setTextColor(Color.WHITE);
			}
		}
	
		LL1 = (LinearLayout)findViewById(R.id.LinearLayout2);
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(150, 70);
			
		TextView tv = new TextView(this);
		tv.setText("Categories:");
		tv.setTextColor(Color.WHITE);
		tv.setGravity(Gravity.LEFT);
		tv.setTextSize(20);
		LL1.addView(tv);
		
		//check if database exist, if not, then create new
		db = new DataBaseHelper(getApplicationContext());
		if(!checkDatabase()){
		    initializeDB(db);
		}
		
		List<Category> cat_list = db.getAllCategories();
		task_list = db.getAllTasks();
		
		button_categories = new Button[cat_list.size()];
		textview_tasks = new TextView[task_list.size()];
		setTextView();
		
		for(int i=0; i<cat_list.size(); i++){
			button_categories[i] = new Button(this);
			button_categories[i].setId(i);
			button_categories[i].setOnClickListener(this);
			button_categories[i].setText(cat_list.get(i).getName());
			button_categories[i].setLayoutParams(layoutParams);
			button_categories[i].setBackgroundColor(Color.WHITE);
			button_categories[i].setPadding(5, 5, 0, 5);
			LL1.addView(button_categories[i]);
		}
		
		button_categories[currentCategory].setBackgroundColor(Color.parseColor("#00C4CD"));
		
		iv_tasks = new ImageView[3][3];
		
		for(int i=0; i<3; i++){
			for(int j=0; j<3; j++){
				iv_tasks[i][j] = new ImageView(this);
				
				Bitmap bm = null;
				String s = task_list.get(9*currentCategory+3*i+j).getImageRef();
				if(s == ""){
					bm = BitmapFactory.decodeResource(getResources(), R.drawable.icon_capture);
				}else{
					bm = BitmapFactory.decodeFile(s);
				}
				Bitmap bmscaled = Bitmap.createScaledBitmap(bm, 120, 120, true);
				
				iv_tasks[i][j].setImageBitmap(bmscaled);
				iv_tasks[i][j].setId(100+3*i+j);
				iv_tasks[i][j].setOnClickListener(this);
			}
		}
		
		TableLayout tablelayout = (TableLayout)findViewById(R.id.TableLayout1);
		TableRow[] tablerow = new TableRow[6];
		
		for(int i=0; i<3; i++){
			tablerow[i*2] = new TableRow(this);
			tablerow[i*2+1] = new TableRow(this);
			for(int j=0; j<3; j++){
					tablerow[i*2].setPadding(0, 15, 0, 0);
					tablerow[i*2+1].setPadding(0, 0, 0, 15);
					tablerow[i*2].addView(textview_tasks[i*3+j]);
					tablerow[i*2+1].addView(iv_tasks[i][j]);
			}
			tablelayout.addView(tablerow[i*2]);
			tablelayout.addView(tablerow[i*2+1]);
		}	
		
		db.closeDB();
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_assignment, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){		
		case 0:
		case 1:
		case 2:
		case 3:
		case 4:
			button_categories[currentCategory].setBackgroundColor(Color.WHITE);
			currentCategory = v.getId();
			button_categories[currentCategory].setBackgroundColor(Color.parseColor("#00C4CD"));
			updateTextView();
			updateImageView();
			break;
		case 100:
		case 101:
		case 102:
		case 103:
		case 104:
		case 105:
		case 106:
		case 107:
		case 108:
		case 109:
			int temp = v.getId()-100;
			a = temp/3;
			b = temp%3;
			String s = task_list.get(9*currentCategory+3*a+b).getImageRef(); 
			if( s == ""){
				dispatchTakePictureIntent();
				galleryAddPic();
			}else{
				Intent intent = new Intent(this, FullScreenImageActivity.class);
				intent.putExtra("image_path", s);
				intent.putExtra("image_name", task_list.get(9*currentCategory+3*a+b).getName());
				intent.putExtra("image_pos", 0);
				startActivity(intent);
			}
			break;
		}
	}
	
	
	//Access the CAMERA MODE
	static final int REQUEST_IMAGE_CAPTURE = 1;
	private void dispatchTakePictureIntent(){
	    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	    // Ensure that there's a camera activity to handle the intent
	    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
	        // Create the File where the photo should go
	        File photoFile = null;
	        try {
	            photoFile = createImageFile();
	        } catch (IOException ex){
	            // Error occurred while creating the File
//Toast.makeText(AssignmentActivity.this, "HERE EXCEPTION", Toast.LENGTH_LONG).show();
	        }
	        // Continue only if the File was successfully created
	        if (photoFile != null){
	            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
	                    Uri.fromFile(photoFile));
	            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
//Toast.makeText(AssignmentActivity.this, "HERE", Toast.LENGTH_LONG).show();
	        }
	    }
	}	
		
	//add photo to gallery
	private void galleryAddPic(){
	    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
	    File f = new File(mCurrentPhotoPath);
	    Uri contentUri = Uri.fromFile(f);
	    mediaScanIntent.setData(contentUri);
	    this.sendBroadcast(mediaScanIntent);
	}
	
	//get image from camera mode after taking picture
	private static int a = 0, b = 0;
	//@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		super.onActivityResult(requestCode, resultCode, data);
		
	        Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
	        Bitmap scaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 120, 120, true);
	        iv_tasks[a][b].setImageBitmap(scaledBitmap);
			iv_tasks[a][b].invalidate();	  
			
			task_list.get(9*currentCategory+3*a+b).setImageRef(mCurrentPhotoPath);
			
			DataBaseHelper db = new DataBaseHelper(getApplicationContext());
			int x = db.updateTask(task_list.get(9*currentCategory+3*a+b));
Toast.makeText(AssignmentActivity.this, "HERE "+Integer.toString(x), Toast.LENGTH_LONG).show();
			db.close();
			
			String xx = task_list.get(9*currentCategory+3*a+b).getImageRef();
//Toast.makeText(AssignmentActivity.this, xx, Toast.LENGTH_LONG).show();
	}
	
	//create image File from data acquired from camera
	String mCurrentPhotoPath;
	private File createImageFile() throws IOException{
	    // Create an image file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	    String imageFileName = "JPEG_" + timeStamp + "_";
	    File storageDir = Environment.getExternalStoragePublicDirectory(
	            Environment.DIRECTORY_PICTURES);
	    File image = File.createTempFile(
	        imageFileName,  /* prefix */
	        ".jpg",         /* suffix */
	        storageDir      /* directory */
	    );

	    //save a file: path for use with ACTION_VIEW intents
	    mCurrentPhotoPath = image.getAbsolutePath();
	    return image;
	}
	
	//initialize task text params
	public void setTextView(){
		for(int i=0; i<9; i++){
			textview_tasks[i] = new TextView(this);
			String s = task_list.get(i).getName();
			textview_tasks[i].setText(s);
			textview_tasks[i].setTextColor(Color.WHITE);
			textview_tasks[i].setGravity(Gravity.CENTER);
			textview_tasks[i].setWidth(100);
			textview_tasks[i].setHeight(10);
			textview_tasks[i].setLines(2);
			textview_tasks[i].setLineSpacing(0.1f,1.4f);
		}
	}
	
	//update task text
	public void updateTextView(){
		int aa = 9*currentCategory;
		for(int i=0; i<9; i++){
			textview_tasks[i].setText(task_list.get(aa+i).getName());
		}
	}
	
	//update task images
	public void updateImageView(){
		int bb = 9*currentCategory;
		for(int i=0; i<3; i++){
			for(int j=0; j<3; j++){
				Bitmap bm = null;
				String s = task_list.get(bb+3*i+j).getImageRef();
				if(s == ""){
					bm = BitmapFactory.decodeResource(getResources(), R.drawable.icon_capture);
				}else{
					bm = BitmapFactory.decodeFile(s);
				}
				Bitmap bmscaled = Bitmap.createScaledBitmap(bm, 120, 120, true);	
				iv_tasks[i][j].setImageBitmap(bmscaled);
			}
		}
	}

	//create database
	private void initializeDB(DataBaseHelper db){
		
		//categories
		db.createCategory(new Category(1, "City"));
		db.createCategory(new Category(1, "School"));
		db.createCategory(new Category(1, "Friends"));
		
		//CITY
		db.createTask(new Task("Bridge"));//1
		db.createTask(new Task("Most highest building"));//2
		db.createTask(new Task("Biggest shopping mall"));//3
		db.createTask(new Task("Square park"));//4
		db.createTask(new Task("Most visited place"));//5
		db.createTask(new Task("Favourite restaurant"));//6
		db.createTask(new Task("Stadium"));//7
		db.createTask(new Task("Highest place"));//8
		db.createTask(new Task("Rush hour"));//9

		//SCHOOL
		db.createTask(new Task("Class"));//1
		db.createTask(new Task("Canteen"));//2
		db.createTask(new Task("Library"));//3
		db.createTask(new Task("Toilet"));//4
		db.createTask(new Task("Kitchen"));//5
		db.createTask(new Task("Hall"));//6
		db.createTask(new Task("Entrance"));//7
		db.createTask(new Task("My fav spot"));//8
		db.createTask(new Task("Sport field"));//9
		
		//FRIENDS
		db.createTask(new Task("Best friend"));//1
		db.createTask(new Task("Talkative"));//2
		db.createTask(new Task("Organized"));//3
		db.createTask(new Task("Cutest"));//4
		db.createTask(new Task("Most shy"));//5
		db.createTask(new Task("I Like"));//6
		db.createTask(new Task("Loner"));//7
		db.createTask(new Task("Smartest"));//8
		db.createTask(new Task("Annoying"));//9
			
	}
	
	public boolean checkDatabase(){
		SQLiteDatabase checkDB = null;
	    boolean result = false;
	    try{
	    	File database_path= getApplicationContext().getDatabasePath("AssignmentMenu");
	    	checkDB = SQLiteDatabase.openDatabase(database_path.toString(), null, SQLiteDatabase.OPEN_READONLY);
	    	result = true;
	    	checkDB.close();
	    }catch(Exception e){
	    	 result = false;
	    }
	    return result;
	}
	
//Toast.makeText(getApplicationContext(), Boolean.toString(checkDatabase()), Toast.LENGTH_LONG).show();

//END	
}
